package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public void buildArticle2Minio(ApArticle apArticle, String content) {
        if (StringUtils.isBlank(content)) {
            return;
        }
        try {
            //2. 使用freemarker生成静态HTML页面
            //2.1 定义数据模型
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("content", JSON.parseArray(content));
            //2.2 加载模板
            Template template = configuration.getTemplate("article.ftl");
            //2.3 生成页面
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);

            //3. 将静态HTML页面上传到minio
            ByteArrayInputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String url = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);
            System.out.println(url);

            //4. 修改文章表, 回填静态URL地址
            apArticle.setStaticUrl(url);

            apArticleMapper.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("生成静态网页失败, 文章id:{},失败原因:{}", apArticle.getId(), e.getMessage());
        }
    }
}
